<template>
  <div class="main">
    <el-container class="container">
      <el-header class="header">
        <div class="logo">
          <span>数据后台</span>
        </div>
      </el-header>
      <el-container>
        <el-aside width="200px" class="aside">
          <el-menu default-active="1" :default-openeds="['1', '1-1']" class="el-menu-vertical-demo" @open="handleOpen"
            @close="handleClose" style="height: 100%;">
            <el-sub-menu index="1" popper-class="dark-mode">
              <template #title>
                <el-icon>
                  <location />
                </el-icon>
                <span>淘宝</span>
              </template>

              <el-sub-menu index="1-1">
                <template #title><span>淘宝数据</span></template>
                <!-- <el-menu-item @click="clickMenu" index="1-1-1">手机端</el-menu-item> -->
                <el-menu-item @click="clickMenu" index="1-1-2">PC端</el-menu-item>
              </el-sub-menu>
              <el-sub-menu index="1-2">
                <template #title><span>1688数据</span></template>
                <el-menu-item @click="clickMenu" index="1-2-1">商品数据</el-menu-item>
                <el-menu-item @click="clickMenu" index="1-2-2">店铺数据</el-menu-item>
              </el-sub-menu>
              <el-sub-menu index="1-3">
                <template #title><span>IP</span></template>
                <el-menu-item @click="clickMenu" index="1-3-1">商品排行</el-menu-item>
              </el-sub-menu>
              <el-sub-menu index="1-4">
                <template #title><span>品类</span></template>
                <el-menu-item @click="clickMenu" index="1-4-1">品类</el-menu-item>
              </el-sub-menu>
            </el-sub-menu>
            <el-sub-menu index="2" popper-class="dark-mode">
              <template #title>
                <el-icon>
                  <location />
                </el-icon>
                <span>小红书</span>

              </template>
              <el-menu-item @click="clickMenu" index="2-1"><router-link
                  :to="{ name: 'xhsOSS' }">OSS资源下载</router-link></el-menu-item>
              <el-menu-item @click="clickMenu" index="2-2">笔记素材</el-menu-item>
              <el-menu-item @click="clickMenu" index="2-3">小红书账号</el-menu-item>
            </el-sub-menu>
            <el-sub-menu index="3" popper-class="dark-mode">
              <template #title>
                <el-icon>
                  <location />
                </el-icon>
                <router-link :to="{ name: 'task' }">任务管理</router-link>
              </template>
            </el-sub-menu>
          </el-menu>
        </el-aside>
        <el-main>
          <el-card class="box-card">
            <el-form :inline="true" class="demo-form-inline">
              <el-form-item>
                <el-button @click="refreshData" type="primary">刷新</el-button>
              </el-form-item>
              <el-form-item>
                <el-button @click="clickShowDialog('dailogTbTaskCfg')" type="primary">创建任务</el-button>
              </el-form-item>
              <template v-if="TbCfg.name == 'TbItmTbCfg'">
                <el-form-item>
                  <el-drawer v-model="drawer" title="筛选" :before-close="handleClosedrawer">
                    <el-form :model="status" label-width="auto" style="max-width: 600px">
                      <el-form-item label="更新时间">
                        <el-date-picker v-model="updateTime" type="date" placeholder="请选择更新时间"
                          :disabled-date="disabledDate" :shortcuts="shortcuts" :size="size" />
                      </el-form-item>
                      <el-form-item label="商品ID">
                        <el-input placeholder="多个id之间用英文逗号隔开" v-model="status.item_id" />
                      </el-form-item>
                      <el-form-item label="我方商品ID">
                        <el-input placeholder="多个id之间用英文逗号隔开" v-model="status.my_item_id" />
                      </el-form-item>
                      <el-form-item label="商品名称">
                        <el-input placeholder="支持模糊搜索" v-model="status.title" />
                      </el-form-item>
                      <el-form-item label="品类id">
                        <el-input placeholder="多个id之间用英文逗号隔开" v-model="status.categ_id" />
                      </el-form-item>
                      <!-- <el-form-item label="是否已导出">
                        <el-radio-group v-model="status.is_export">
                          <el-radio value=true>是</el-radio>
                          <el-radio value=false>否</el-radio>
                          <el-radio value=all>全部</el-radio>
                        </el-radio-group>
                      </el-form-item> -->
                      <!-- <el-form-item label="是否已编辑">
                        <el-radio-group v-model="status.is_edit">
                          <el-radio value=true>是</el-radio>
                          <el-radio value=false>否</el-radio>
                          <el-radio value=all>全部</el-radio>
                        </el-radio-group>
                      </el-form-item> -->
                      <!-- <el-form-item label="商品来源">
                        <el-select
                          v-model="status.type"
                          placeholder="Select"
                          style="width: 240px"
                        >
                          <el-option
                            v-for="item in TbCfg.searchOption"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value"
                          />
                        </el-select>
                      </el-form-item> -->
                    </el-form>
                    <div class="demo-drawer__footer">
                      <el-button @click="cancelDrawerForm">取消</el-button>
                      <el-button type="primary" @click="onClickSend">
                        确定
                      </el-button>
                    </div>
                  </el-drawer>
                  <el-button type="primary" style="margin-left: 16px" @click="drawer = true">筛选/查询</el-button>
                  <!-- <el-button @click="getData(currentMenu)" type="primary">查询</el-button> -->
                </el-form-item>
                <el-form-item>
                  <el-button @click="downloadPakage" type="primary">下载包</el-button>
                </el-form-item>
                <el-form-item>
                  <el-button @click="updateEditStatus" type="primary">确认编辑</el-button>
                </el-form-item>
              </template>
              <el-form-item v-if="currentMenu === '1-4-1'">
                <el-button @click="clickShowDialog('dailogCategoryCfg')" type="primary">新增品类</el-button>
              </el-form-item>
            </el-form>
            <el-table ref="multipleTableRef" :data="status.tableData" show-overflow-tooltip
              @selection-change="handleSelectionChange">
              <el-table-column type="selection" width="55" />
              <template v-for="item in TbCfg.items ">
                <el-table-column :type="item.type" :label="item.label" :width="item.width" v-if="item.type">
                  <template v-slot="index_scope" v-if="item.scope">
                    <span>{{ (status.page - 1) * status.pageSize + index_scope.$index + 1 }}</span>
                  </template>
                </el-table-column>
                <el-table-column :fixed="item.fixed" :label="item.label" :width="item.width" v-else-if="item.fixed">
                  <template v-slot="tb_delete_scope" v-if="item.scope == 'tb_delete_scope'">
                    <el-button link type="primary" size="small"
                      @click="clickShowDialog('deleteItem', tb_delete_scope.row.id)">删除</el-button>
                  </template>
                  <template v-slot="category_delete" v-if="item.scope == 'category_delete'">
                    <el-button link type="primary" size="small"
                      @click="clickShowDialog('deleteItem', category_delete.row.id)">删除</el-button>
                    <el-button link type="primary" size="small"
                      @click="clickShowDialog('dailogCategoryUpdate', category_delete.row)">修改</el-button>
                  </template>
                  <!-- <template v-slot="xhs_account_scope" v-if="item.scope == 'xhs_account_scope'">
                    <el-button size="small" type="primary"
                      @click="clickShowDialog('dailogTbTaskCfg', xhs_account_scope.row)">发布笔记</el-button>
                    <el-button size="small" type="primary"
                      @click="clickShowDialog('dailogTbTaskCfg', xhs_account_scope.row)">互助涨粉</el-button>
                    <el-button size="small" type="primary"
                      @click="clickShowDialog('dailogTbTaskCfg', xhs_account_scope.row)">账号训练</el-button>
                  </template> -->
                </el-table-column>
                <el-table-column v-else :prop='item.prop' :label="item.label" :width="item.width">
                  <template v-slot="ip_scope" v-if="item.scope == 'ip_scope'">
                    <div style="display: inline-block;width:30px">
                      <el-button size="small" type="primary"
                        @click="getCategoryList(ip_scope.$index, ip_scope.row)">查看品类排行</el-button>
                    </div>
                  </template>
                  <template v-slot="top10_list" v-if="item.scope == 'top10_list'">
                    <div style="display: inline-block;width:30px"><span>{{ top10_list.row.current_num }}</span></div>
                    <el-button size="small" type="primary" @click="getT10(top10_list.row)">查看T10商品</el-button>
                  </template>
                  <template v-slot="supplier_list" v-if="item.scope == 'supplier_list'">
                    <div style="display: inline-block;width:30px"><span>{{ supplier_list.row.current_supplier_num
                        }}</span></div>
                    <el-button size="small" type="primary"
                      @click="handleSee(supplier_list.$index, supplier_list.row)">查看供应商</el-button>
                  </template>
                  <template v-slot="tb_type_scope" v-if="item.scope == 'tb_type_scope'">
                    <span>{{ sourceMap[tb_type_scope.row.type] }}</span>
                  </template>
                  <template v-slot="tb_itm_scope" v-if="item.scope == 'tb_itm_scope'">
                    <el-link target="_blank" :href="`https://item.taobao.com/item.htm?id=${tb_itm_scope.row.item_id}`"
                      type="primary" :underline="false">{{ tb_itm_scope.row.item_id }}</el-link>
                  </template>
                  <template v-slot="tb_my_itm_scope" v-if="item.scope == 'tb_my_itm_scope'">
                    <el-link target="_blank"
                      :href="`https://item.taobao.com/item.htm?id=${tb_my_itm_scope.row.my_item_id}`" type="primary"
                      :underline="false">{{ tb_my_itm_scope.row.my_item_id }}</el-link>
                  </template>
                  <template v-slot="tb_1688_offer_link" v-if="item.scope == 'tb_1688_offer_link'">
                    <el-link target="_blank"
                      :href="`https://detail.1688.com/offer/${tb_1688_offer_link.row.offer_id}.html`" type="primary"
                      :underline="false">{{ tb_1688_offer_link.row.offer_id }}</el-link>
                  </template>
                  <template v-slot="tb_sp_scope" v-if="item.scope === 'tb_sp_scope'">
                    <el-link target="_blank" :href="tb_sp_scope.row.shop_url" type="primary" :underline="false">{{
                      tb_sp_scope.row.shop_url }}</el-link>
                  </template>
                  <template v-slot="tb_1688_shop_link" v-if="item.scope === 'tb_1688_shop_link'">
                    <el-link target="_blank" :href="tb_1688_shop_link.row.shop_url" type="primary" :underline="false">{{
                      tb_1688_shop_link.row.shop_url }}</el-link>
                  </template>
                  <!-- <template v-slot="img" v-if="item.scope === 'img'">
                    <el-popover placement="top-start" :title="img.row.title" :width="425" trigger="hover">
                      <template #reference>
                        <el-image style="width: 40px; height: 40px"
                          :src="img.row.img"
                          :fit="fit" />
                      </template>
                      <el-image style="width: 400px; height: 400px" :src="img.row.img" :fit="fit" />
                    </el-popover>
                  </template> -->
                </el-table-column>
              </template>
            </el-table>
            <el-pagination v-model:current-page="status.page" v-model:page-size="status.pageSize"
              :page-sizes="[20, 50, 100, 200, 300, 400]" layout="total, sizes, prev, pager, next" :total="status.total"
              @prev-click='prevClick' @next-click='nextClick' @current-change='currentChange'
              @size-change="handleSizeChange" />
            <el-dialog v-model="dailogTbCfg.dialog_visible" :title="dailogTbCfg.title" width="500" @close="dialogClose">
              <template v-if="dailogTbCfg.name === 'dailogTbTaskCfg' | dailogTbCfg.name === 'XHS_INCREACE_fOLLOWERS'">
                <div v-for="item, index in dailogTbCfg.select_item">
                  <span style="display: inline-block ;width: 70px;">{{ item.label }}</span>
                  <el-select v-if="item.options" v-model="dailogTbCfg.form_model[item.model]"
                    :filterable="item.filterable" :remote-method="remoteMethod" :loading="item.loading" :disabled="item.disabled"
                    :remote="item.remote" @focus="focusSelect(index)" @change="selectChange" :placeholder="`请选择${item.label}`"
                    size="large" style="width: 240px">
                    <el-option v-for="i in item.options" :key="i.value" :label="i.label" :value="i.value" />
                  </el-select>
                </div>
                <el-form :model="dailogTbCfg.form_model">
                  <el-form-item :label="item.label" :label-width="120" v-for="item in dailogTbCfg.form_item">
                    <el-input width="100px" v-model="dailogTbCfg.form_model[item.model]" autocomplete="off" :disabled="item.disabled" />
                  </el-form-item>
                </el-form>
              </template>
              <template v-if="dailogTbCfg.name === 'dailogCategoryCfg' | dailogTbCfg.name === 'dailogCategoryUpdate'">
                <el-form :model="dailogTbCfg.form_model">
                  <el-form-item :label="item.label" :label-width="formLabelWidth" v-for="item in dailogTbCfg.form_item">
                    <el-input v-model="dailogTbCfg.form_model[item.model]" autocomplete="off" :disabled="item.disabled" />
                  </el-form-item>
                </el-form>
              </template>
              <template v-if="dailogTbCfg.name === 'deleteItem'">
                <span>
                  {{ dialog_map[currentMenu].title }}
                </span>
              </template>
              <template #footer>
                <div class="dialog-footer">
                  <el-button @click="dailogTbCfg.dialog_visible = false">取消</el-button>
                  <el-button type="primary" @click="clickConfirm">
                    确认
                  </el-button>
                </div>
              </template>
            </el-dialog>
            <el-dialog v-model="T10dialogTableVisible" :title="dailogTbCfg.title" :width="dailogTbCfg.width">
              <el-form>
                <el-form-item>
                  <el-button @click="downloadPakage" type="primary">下载包</el-button>
                </el-form-item>
              </el-form>
              <el-table :data="getT10List" ref="multipleTableRef" style="width: 100%" show-overflow-tooltip
                @selection-change="handleSelectionChange">
                <el-table-column v-show="dailogTbCfg.selectable" type="selection" width="55" />
                <template v-for="item in dailogTbCfg.items ">
                  <el-table-column :type="item.type" :label="item.label" :width="item.width" v-if="item.type">
                    <template v-slot="index_scope" v-if="item.scope">
                      <span>{{ index_scope.$index + 1 }}</span>
                    </template>
                  </el-table-column>
                  <el-table-column :fixed="item.fixed" :label="item.label" :width="item.width" v-else-if="item.fixed">
                    <template v-slot="tb_delete_scope" v-if="item.scope == 'tb_delete_scope'">
                      <el-button link type="primary" size="small"
                        @click="deleteItem(tb_delete_scope.row.id)">删除</el-button>
                    </template>
                  </el-table-column>
                  <el-table-column v-else :prop="item.prop" :label="item.label" :width="item.width">
                    <template v-slot="top10_list" v-if="item.scope == 'top10_list'">
                      <div style="display: inline-block;width:30px"><span>{{ top10_list.row.current_num }}</span></div>
                      <el-button size="small" type="primary" @click="getT10(top10_list.row)">查看T10商品</el-button>
                    </template>
                    <template v-slot="tb_itm_scope" v-if="item.scope == 'tb_itm_scope'">
                      <el-link target="_blank" :href="`https://item.taobao.com/item.htm?id=${tb_itm_scope.row.item_id}`"
                        type="primary" :underline="false">{{ tb_itm_scope.row.item_id }}</el-link>
                    </template>
                    <template v-slot="tb_sp_scope" v-if="item.scope === 'tb_sp_scope'">
                      <el-link target="_blank" :href="tb_sp_scope.row.shop_url" type="primary" :underline="false">{{
                        tb_sp_scope.row.shop_url }}</el-link>
                    </template>
                    <template v-slot="main_imgs" v-if="item.scope === 'main_imgs'">
                      <el-popover placement="top-start" :title="main_imgs.row.title" :width="400" trigger="hover">
                        <template #reference>
                          <el-image style="width: 40px; height: 40px" :src="main_imgs_list(main_imgs.row.main_imgs)[0]"
                            :fit="fit" />
                        </template>
                        <el-carousel :interval="5000" arrow="always">
                          <el-carousel-item v-for="item in main_imgs_list(main_imgs.row.main_imgs)" :key="item">
                            <el-image style="width: 400px; height: 400px" :src="item" :fit="fit" />
                          </el-carousel-item>
                        </el-carousel>
                      </el-popover>
                    </template>
                  </el-table-column>
                </template>
              </el-table>
            </el-dialog>
          </el-card>
        </el-main>
      </el-container>
    </el-container>
    <!-- <supplier></supplier> -->
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { Location } from '@element-plus/icons-vue'

import api from '@/api/index.js'
import Tbconfig from './config'

const currentRowId = ref()
const currentIPId = ref()
const multipleTableRef = ref()
const multipleSelection = ref([])
const currentMenu = ref('1-1-2') // 当前的菜单
const TbCfg = ref({}) // 表单配置
const dailogTbCfg = ref({}) // 表单配置
const centerDialogVisible = ref(false) // 删除提示框是否显示
const currentItem = ref(null)
const T10dialogTableVisible = ref(false)   // 新增品类提示框是否显示
const formLabelWidth = '140px'
const categoryDialogStatus = ref(0)
const supplierList = ref([])
const getT10List = ref([])
const drawer = ref(false)
const size = ref('default')
const updateTime = ref()
const focusIndex = ref()
const originalObject = ref()
const copiedObject = ref()

const status = reactive({
  tableData: [],
  pageSize: 10,
  total: 0,
  page: 1,
  keyword: "",
  is_edit: null,
  is_export: null,
  item_id: null,
  my_item_id: null,
  title: null,
  update_time: null,
  categ_id: null
})


const dialogClose=()=>{
  Tbconfig=originalObject.value
}

const focusSelect = (index) => {
  focusIndex.value = index
}
const selectChange=(e)=>{
  if (dailogTbCfg.value.select_item[focusIndex.value].model == "ip_id"){
    const targetElement = dailogTbCfg.value.select_item[focusIndex.value].options.find((element) => element.value === e);
    dailogTbCfg.value.select_item[focusIndex.value+1].disabled=false;
    dailogTbCfg.value.form_item[3].disabled=true;
    dailogTbCfg.value.form_model.search_words=targetElement.label
  }
  if (dailogTbCfg.value.select_item[focusIndex.value].model == "dingyu"){
    const targetElement = dailogTbCfg.value.select_item[focusIndex.value].options.find((element) => element.value === e);
    dailogTbCfg.value.select_item[focusIndex.value+1].disabled=false;
    dailogTbCfg.value.form_model.search_words=dailogTbCfg.value.form_model.search_words + targetElement.label
  }
  if (dailogTbCfg.value.select_item[focusIndex.value].model == "xingwei"){
    const targetElement = dailogTbCfg.value.select_item[focusIndex.value].options.find((element) => element.value === e);
    dailogTbCfg.value.form_model.search_words=dailogTbCfg.value.form_model.search_words + targetElement.label
  }

}
const remoteMethod = (query) => {
  dailogTbCfg.value.select_item[focusIndex.value]
  if (query) {
    dailogTbCfg.value.select_item[focusIndex.value].loading = true
    setTimeout(() => {
      dailogTbCfg.value.select_item[focusIndex.value].loading = false
      api.getIPs({ IP: query }).then(res => {
        if (res.data.status === 200) {
          dailogTbCfg.value.select_item[focusIndex.value].options = res.data.data.data.map((item) => {
            return { value: item.id, label: item.ip }
          })
        }
      })
    }, 200)
  } else {
    dailogTbCfg.value.select_item[focusIndex.value].options = []
  }
}

const clickConfirm = () => {
  const data = {
    category: dailogTbCfg.value.form_model.category,
    category_id: Number(dailogTbCfg.value.form_model.category_id),
    target_item_num: Number(dailogTbCfg.value.form_model.target_item_num),
    target_supplier_num: Number(dailogTbCfg.value.form_model.target_supplier_num)
  }
  if (dailogTbCfg.value.name === "dailogCategoryCfg") {
    if (categoryDialogStatus.value == 0) {
      api.add_category(data).then(res => {
        if (res.status == 200) {
          dailogTbCfg.value.dialog_visible = false
          getData(currentMenu.value)
        }
      })
    }
  } else if (dailogTbCfg.value.name === "dailogTbTaskCfg") {
    if (dailogTbCfg.value.form_model.task_type === "TB_ITEM_UPDATE" | dailogTbCfg.value.form_model.task_type === "XHS_AUTO_ACCOUNT_TRAINING") {
      dailogTbCfg.value.form_model.paramaters = multipleSelection.value.map(i => {
        return { id: i.id }
      })
    } else if (dailogTbCfg.value.form_model.task_type === "XHS_AUTO_PUBLISH_NOTE" || dailogTbCfg.value.form_model.task_type === "CHECK_FOLLOWER") {
      dailogTbCfg.value.form_model.paramaters = multipleSelection.value.map(i => {
        return { ...i, xhs_account: dailogTbCfg.value.form_model.xhs_account }
      })
    } else if (dailogTbCfg.value.form_model.task_type === "XHS_INCREACE_fOLLOWERS") {
      dailogTbCfg.value.form_model.paramaters = multipleSelection.value.map(i => {
        return { ...i, xhs_account: dailogTbCfg.value.form_model.xhs_account }
      })
      copiedObject.value = JSON.parse(JSON.stringify(dailogTbCfg.value));
      clickShowDialog('subDailog.XHS_INCREACE_fOLLOWERS')
      return
    }
    api.create_task(dailogTbCfg.value.form_model).then(res => {
      dailogTbCfg.value.dialog_visible = false
      console.log(res)
    })
  } else if (dailogTbCfg.value.name === "deleteItem") {
    dialog_map[currentMenu][method](currentItem.value.id)
  } else if (dailogTbCfg.value.name === "dailogCategoryUpdate") {
    api.update_category(data, currentItem.value.id).then(res => {
        if (res.status == 200) {
          console.log(res)
          dailogTbCfg.value.dialog_visible = false
          getData(currentMenu.value)
        }
      })
  } else if (dailogTbCfg.value.name === "XHS_INCREACE_fOLLOWERS") {
    api.create_task({
      ...copiedObject.value.form_model,
      paramaters: copiedObject.value.form_model.paramaters.map(i => { return { ...i, ...dailogTbCfg.value.form_model } })
    }).then(res => {
      dailogTbCfg.value.dialog_visible = false
      console.log(res)
    })
  }
  Tbconfig=originalObject.value
}


const clickShowDialog = (dialog_name, args = null) => {
  if (dialog_name === 'dailogCategoryCfg') {
    dailogTbCfg.value = Tbconfig.dailogCategoryCfg
    categoryDialogStatus.value = 0
  } else if (dialog_name === 'dailogTbTaskCfg') {
    if (multipleSelection.value.length == 0) {
      ElMessage('请勾选要创建任务的主体')
      return
    }
    dailogTbCfg.value = Tbconfig.dailogTbTaskCfg
  } else if (dialog_name === 'deleteItem') {
    dailogTbCfg.value = Tbconfig.deleteItem
    categoryDialogStatus.value = 0;
    currentItem.value = args
  } else if (dialog_name === 'dailogCategoryUpdate') {
    dailogTbCfg.value = Tbconfig.dailogCategoryUpdate
    categoryDialogStatus.value = 1
    currentItem.value = args
    dailogTbCfg.value.form_model.category = args.category
    dailogTbCfg.value.form_model.category_id = args.category_id
    dailogTbCfg.value.form_model.target_item_num = args.target_item_num
    dailogTbCfg.value.form_model.target_supplier_num = args.target_supplier_num
  } else if (dialog_name === 'subDailog.XHS_INCREACE_fOLLOWERS') {
    dailogTbCfg.value = Tbconfig.subDailog.XHS_INCREACE_fOLLOWERS
  }
  dailogTbCfg.value.dialog_visible = true
}

const main_imgs_list = (imgsstr) => {
  if (imgsstr !== null && imgsstr !== undefined) {
    const regex = /https:\/\/.*?jpg/g;
    return imgsstr.match(regex) ? imgsstr.match(regex) : [''];
  } else {
    return ['']
  }
}
const sourceMap = ref({
  0: "PC淘宝搜索",
  1: "PC淘宝首页推荐",
  2: "手机淘宝首页推荐",
  100: "全部"
})
const shortcuts = [
  {
    text: '今天',
    value: new Date(),
  },
  {
    text: '昨天',
    value: () => {
      const date = new Date()
      date.setTime(date.getTime() - 3600 * 1000 * 24)
      return date
    },
  },
  {
    text: '一周前',
    value: () => {
      const date = new Date()
      date.setTime(date.getTime() - 3600 * 1000 * 24 * 7)
      return date
    },
  },
]
const disabledDate = (time) => {
  return time.getTime() > Date.now()
}

const handleSizeChange = (val) => {
  status.pageSize = val
  getData(currentMenu.value)
}

const onClickSend = () => {
  if (updateTime._value) {
    const date = new Date(updateTime._value);
    const formattedDate = `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}`;
    status.update_time = formattedDate
  }
  api.get_taobao_items({ ...status }).then(res => {
    if (res.status == 200) {
      status.tableData = res.data.data.data
      status.pageSize = res.data.data.per_page,
        status.total = res.data.data.total
      drawer.value = false
    }
  })

}

const cancelDrawerForm = (formEl) => {
  drawer.value = false;
}

const handleClosedrawer = (done) => {
  done()
}
const handleSelectionChange = (val) => {
  multipleSelection.value = val
}

const downloadPakage = () => {
  if (multipleSelection.value.length == 0) {
    ElMessage('请勾选要下载的商品')
    return
  }
  api.download_pakage({ 'ids': multipleSelection.value.map(i => i.id) }).then(response => {
    const url = window.URL.createObjectURL(new Blob([response.data]));
    const link = document.createElement('a');
    link.href = url;
    link.setAttribute('download', 'your_archive.zip');
    document.body.appendChild(link);
    link.click();
    getData(currentMenu.value)
    ElMessage({
      message: '下载成功.',
      type: 'success',
    })
  })
    .catch(error => {
      ElMessage({
        message: '下载失败.',
        type: 'erro',
      })
      console.error('下载失败：', error);
    });
}


const updateEditStatus = () => {
  if (multipleSelection.value.length == 0) {
    ElMessage('请勾选已编辑的商品')
    return
  }
  multipleSelection.value.forEach(i => {
    api.update_taobao_item({ 'id': i.id, 'is_edit': true }).then(res => {
      console.log(res)
    })
    getData(currentMenu.value)
  })
}

onMounted(() => {
  originalObject.value = JSON.parse(JSON.stringify(Tbconfig));
  getData(currentMenu.value)
})

const refreshData = () => {
  status.pageSize = 10
  status.page = 1
  getData(currentMenu.value)
}


const getT10 = (row) => {
  currentRowId.value = row.id
  dailogTbCfg.value = Tbconfig.T10itemCofig
  if (currentMenu.value == "1-4-1") {
    api.item_rank_by_category({ 'categ_id': row.id }).then(res => {
      if (res.data.status == 200) {
        T10dialogTableVisible.value = true
        getT10List.value = res.data.data
      } else {
        ElMessage({
          message: res.data.msg,
          type: 'warning',
        })
      }
    })
  } else if (currentMenu.value == "1-3-1") {
    api.item_rank_by_category({ 'ip_id': currentIPId.value, 'categ_id': row.id }).then(res => {
      if (res.data.status == 200) {
        T10dialogTableVisible.value = true
        getT10List.value = res.data.data
      } else {
        ElMessage({
          message: res.data.msg,
          type: 'warning',
        })
      }
    })
  }
}

const getCategoryList = (i, row) => {
  dailogTbCfg.value = Tbconfig.categryListCofig
  currentIPId.value = row.id
  api.getCategoryList({ 'ip_id': row.id }).then(res => {
    if (res.data.length > 0) {
      T10dialogTableVisible.value = true
      getT10List.value = res.data
    } else {
      ElMessage({
        message: "暂无排行",
        type: 'warning',
      })
    }
  })
}

const handleSee = (i, row) => {
  api.get_supplier({ 'categ_id': row.id }).then(res => {
    if (res.data.status == 200) {
      supplierList.value = res.data.data
    } else {
      ElMessage({
        message: res.data.msg,
        type: 'warning',
      })
    }
  })
}

// 点击菜单
const clickMenu = (e) => {
  currentMenu.value = e.index
  console.log(e.index)

  status.page = 1
  getData(e.index)
}
// 删除品类
const deleteCategory = () => {
  api.delete_category(currentItemId.value).then(res => {
    if (res.data.status === 200) {
      ElMessage({
        message: '删除成功.',
        type: 'success',
      })
      getData(currentMenu.value)
    } else {
      ElMessage({
        message: '删除失败.',
        type: 'warning',
      })
    }
    centerDialogVisible.value = false
  })
}
// 删除淘宝商品
const deleteItem = (id) => {
  api.del_taobao_items({ id: id }).then(res => {
    if (res.data.status === 200) {
      ElMessage({
        message: '删除成功.',
        type: 'success',
      })
      if (currentMenu.value === "1-3-1") {
        getT10(currentRowId)
      } else if (currentMenu.value === "1-1-2") {
        getData(currentMenu.value)
      } else {
        getT10(currentRowId)
      }
    } else {
      ElMessage({
        message: '删除失败.',
        type: 'warning',
      })
    }
    centerDialogVisible.value = false
  })
}

const dialog_map = reactive({
  '1-4-1': {
    title: "是否确认删除该品类",
    method: deleteCategory
  },
  '1-1-2': {
    title: "请确认是否删除这条商品信息",
    method: deleteItem
  },
  '1-3-1': {
    title: "请确认是否删除这条商品信息",
    method: deleteItem
  }
})

const getData = (i) => {
  const params = {
    "pnum": status.page,
    "psize": status.pageSize,
    'keyword': status.keyword,
    'type': status.type,
    'all_support': status.all_support
  }
  switch (i) {
    case '1-1-2':
      TbCfg.value = Tbconfig.TbItmTbCfg
      api.get_taobao_items({ ...params }).then(res => {
        status.tableData = res.data.data.data
        status.pageSize = res.data.data.per_page,
          status.total = res.data.data.total
      });
      break;
    case '1-2-1':
      TbCfg.value = Tbconfig.Tb1688ItmCfg
      api.get_tb1688_offers({ ...params }).then(res => {
        status.tableData = res.data.data
        status.pageSize = res.data.per_page,
          status.total = res.data.total
      });
      break;
    case '1-3-1':
      TbCfg.value = Tbconfig.IPCfg
      api.getIPs({ ...params }).then(res => {
        status.tableData = res.data.data.data
        status.pageSize = res.data.data.per_page,
          status.total = res.data.data.total
      });
      break;
    case '1-4-1':
      TbCfg.value = Tbconfig.CategoryCfg
      api.get_categories({ ...params }).then(res => {
        console.log(res.data.data)
        status.tableData = res.data.data.data
        status.pageSize = res.data.data.per_page,
          status.total = res.data.data.total
      });
      break;
    case '1-2-2':
      TbCfg.value = Tbconfig.Tb1688ShopCfg
      api.get_tb1688_shops({ ...params }).then(res => {
        status.tableData = res.data.data
        status.pageSize = res.data.per_page,
          status.total = res.data.total
      });
      break;
    case '2-2':
      TbCfg.value = Tbconfig.SourceCaterialCfg
      api.get_source_caterial().then(res => {
        status.tableData = res.data.data
        status.pageSize = res.data.data.length,
          status.total = res.data.data.length
      });
      api.get_xhs_account().then(res => {
        Tbconfig.dailogTbTaskCfg.select_item[2].options = res.data.data.map(i => {
          return { value: i.id, label: i.account_name }
        })
      })
      break;
    case '2-3':
      TbCfg.value = Tbconfig.xhsAccountCfg
      api.get_xhs_account().then(res => {
        Tbconfig.dailogTbTaskCfg.select_item[2].options = res.data.data.map(i => {
          return { value: i.id, label: i.account_name }
        })
        status.tableData = res.data.data
        status.pageSize = res.data.data.length,
          status.total = res.data.data.length
      })
      break;
    default:
      break;
  }

};

const prevClick = (e) => {
  getData(currentMenu.value)
}

const nextClick = (e) => {
  getData(currentMenu.value)
}

const currentChange = (e) => {
  status.page = e
  console.log(e)
  getData(currentMenu.value)
}

const handleOpen = (key, keyPath) => {
  console.log(key, keyPath)
}
const handleClose = (key, keyPath) => {
  console.log(key, keyPath)
}

</script>
<style>
.main {
  height: 100%;
  width: 100%;
  background-color: aquamarine;
}

.box-card {
  width: 99%;
  /* height: 90%; */
}

.aside {
  height: 100%;
  background-color: aquamarine;
}

.header {
  background-color: #fff;
  box-shadow: 0 0 5px rgba(0, 0, 0, 0.3);
  font-size: 20px;
  color: #999;
  height: 50px;
  width: 100%;
}

.logo {
  float: left;
  height: 50px;
  align-items: center;
  display: flex;
  justify-content: center;
}

.container {
  height: 100%;
}

.search-box {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.demo-form-inline .el-input {
  --el-input-width: 220px;
}

.demo-form-inline .el-select {
  --el-select-width: 220px;
}
</style>